package com.shkco.pet.service.impl;

import com.shkco.basic.exception.BusinessException;
import com.shkco.basic.service.IBaiduAiAuditService;
import com.shkco.basic.util.*;
import com.shkco.order.domain.OrderPetAcquisition;
import com.shkco.order.mapper.OrderPetAcquisitionMapper;
import com.shkco.org.domain.Employee;
import com.shkco.org.domain.Shop;
import com.shkco.org.mapper.EmployeeMapper;
import com.shkco.org.mapper.ShopMapper;
import com.shkco.org.service.IEmployeeService;
import com.shkco.pet.domain.Pet;
import com.shkco.pet.domain.PetType;
import com.shkco.pet.domain.SearchMasterMsg;
import com.shkco.pet.domain.SearchMasterMsgAuditLog;
import com.shkco.pet.mapper.PetMapper;
import com.shkco.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.shkco.pet.mapper.SearchMasterMsgMapper;
import com.shkco.pet.query.SearchMasterMsgQuery;
import com.shkco.pet.service.ISearchMasterMsgAuditLogService;
import com.shkco.pet.service.ISearchMasterMsgService;
import com.shkco.basic.service.impl.BaseServiceImpl;
import com.shkco.user.domain.Logininfo;
import com.shkco.user.domain.User;
import com.shkco.user.mapper.UserMapper;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg smm, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        smm.setUserId(user.getId());
        //2.将寻主消息添加到数据库- 如何审核失败 - 修改寻主消息重新审核【shop_id】
        searchMasterMsgMapper.add(smm);
        //3.百度AI智能审核
        Boolean aBoolean = baiduAiAuditService.textAudit(smm.getName() + smm.getTitle());
        Boolean bBoolean = baiduAiAuditService.imageAudit(smm.getResources());
        //3.1.审核成功
        if (aBoolean && bBoolean) {
            //a.修改状态：0 - 1 待处理
            smm.setState(1);
            //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
            List<Shop> shops = shopMapper.findAll();
            // 获取用户坐标
            Point point = DistanceUtils.getPoint(smm.getAddress());
            // 查询哪个店铺离用户最近
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //b2.没有找到店铺 - 放到寻主池
            if (nearestShop != null){
                smm.setShopId(nearestShop.getId());
            }
            //b3.更新数据库
            searchMasterMsgMapper.update(smm);
            //c.添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(smm.getId());
            searchMasterMsgAuditLog.setState(1);
            searchMasterMsgAuditLog.setNote("审核成功！");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);

            // 发送短信给店铺管理员
            if (nearestShop != null){
                smm.setShopId(nearestShop.getId());
                Employee employee = employeeMapper.findByShopId(nearestShop.getId());
//                SmsUtils.sendSms(employee.getPhone(),"您有新的订单，请前往" + smm.getAddress() + "接回宠物");
                System.out.println("您有新的订单，请前往" + smm.getAddress() + "接回宠物");
            }
            return new AjaxResult();

        } else {
            //3.2.审核失败
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(smm.getId());
            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setNote("审核失败！");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            //a.发送短信给用户告诉他审核失败，修改寻主消息
//            SmsUtils.sendSms(user.getPhone(),"您的寻主消息审核失败，请修改寻主消息后重新发布");
            System.out.println("您的寻主消息审核失败，请修改寻主消息后重新发布");
            //b.添加审核失败日志
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        long msgId = Long.parseLong(map.get("msgId"));
        long handler = Long.parseLong(map.get("handler"));
        String note = map.get("note");

        // 根据msgid查询订单
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgId);
        // 判断订单是否已经存在
        if (order != null && order.getState() == 0){
            throw new BusinessException("订单处理中，请勿重复提交");
        }

        // 将订单的宠物录入系统
        SearchMasterMsg msg = searchMasterMsgMapper.findById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.add(pet);

        // 生成收购订单
        OrderPetAcquisition orderPetAcquisition = buildOrderPetAcquisition(msg,pet,handler,note);
        orderPetAcquisitionMapper.add(orderPetAcquisition);

        // 给处理人发送短信收回宠物
//        Employee employee = employeeMapper.findById(handler);
//        SmsUtils.sendSms(employee.getPhone(),"您有新的订单，请及时处理，地址:" + msg.getAddress());
        System.out.println("您有新的订单，请及时处理，地址:" + msg.getAddress());
    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, long handler, String note) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        String sn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        orderPetAcquisition.setOrderSn(sn);
        orderPetAcquisition.setDigest(note);
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 2));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(msg.getPrice());
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setUserId(msg.getUserId());
        orderPetAcquisition.setShopId(msg.getShopId());
        orderPetAcquisition.setAddress(msg.getAddress());
        orderPetAcquisition.setEmpId(handler);
        orderPetAcquisition.setSearchMasterMsgId(msg.getId());
        return orderPetAcquisition;
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setPetType(msg.getType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
